<?php
declare(strict_types=1);


namespace App\Fastapp\Mapper;

use App\Fastapp\Model\FastappRobot;
use Hyperf\Database\Model\Builder;
use Mine\Abstracts\AbstractMapper;
use Mine\Exception\NormalStatusException;
use Telegram\Bot\Api;

/**
 * 机器人列表Mapper类
 */
class FastappRobotMapper extends AbstractMapper
{
    /**
     * @var FastappRobot
     */
    public $model;

    public function assignModel()
    {
        $this->model = FastappRobot::class;
    }

    /**
     * 搜索处理器
     * @param Builder $query
     * @param array $params
     * @return Builder
     */
    public function handleSearch(Builder $query, array $params): Builder
    {
        if (isset($params['shop_id']) && filled($params['shop_id'])) {
            $query->where('shop_id', '=', $params['shop_id']);
        }

        // 机器人token
        if (isset($params['token']) && filled($params['token'])) {
            $query->where('token', 'like', '%' . $params['token'] . '%');
        }

        // 备注
        if (isset($params['remark']) && filled($params['remark'])) {
            $query->where('remark', 'like', '%' . $params['remark'] . '%');
        }
        return $query;
    }

    public function handlePageItems(array $items, array $params): array
    {
        $site_domain = api_cache()->getConfigByGroupKey('site_config')['site_domain'];
        foreach ($items as $item) {
            if (!$item->callback) $item->callback = $site_domain . '/callback/tgbot/' . $item->id;
        }
        return $items;
    }

    public function save(array $data): mixed
    {
        $id = parent::save($data);
        if ($id && $data['type'] == 1) {
            $site_domain = api_cache()->getConfigByGroupKey('site_config')['site_domain'];
            $bot = new Api($data['token']);
            try {
                $bot->setWebhook([
                    'url' => $site_domain . '/callback/tgbot/' . $id,
                    'secret_token' => md5('fastapp' . md5($data['token']))
                ]);
            } catch (\Throwable) {
                $this->model::query()->where(['id' => $id])->delete();
                throw new NormalStatusException('设置失败');
            }
        }
        redis()->hMSet('bot:' . $id, $data);
        if ($data['config'] && method_exists($data['config'], 'init')) $data['config']::init(new \Telegram\Bot\Api($data['token']));
        return $id;
    }

    public function update(mixed $id, array $data): bool
    {
        $s = parent::update($id, $data);
        if ($s) redis()->hMSet('bot:' . $id, $data);
        if ($data['config'] && method_exists($data['config'], 'init')) $data['config']::init(new \Telegram\Bot\Api($data['token']));
        return $s;
    }

    public function delete(array $ids): bool
    {
        $s = parent::delete($ids);
        if ($s) foreach ($ids as $id) redis()->del('bot:' . $id);
        return $s;
    }
}